﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace MyHelper
{
    public class DBHelper
    {
        #region 根据datatable得到实体集合
        public static IEnumerable<T> GetEntityListByTable<T>(DataTable table) where T : class
        {
            List<T> entityList = new List<T>();
            if (table != null && table.Rows.Count > 0)
            {
                foreach (DataRow dr in table.Rows)
                {
                    T entity = (T)Activator.CreateInstance(typeof(T));
                    for (int i = 0; i < dr.Table.Columns.Count; i++)
                    {
                        PropertyInfo propertyInfo = entity.GetType().GetProperty(dr.Table.Columns[i].ColumnName);
                        if (propertyInfo != null && dr[i] != DBNull.Value)
                        {
                            propertyInfo.SetValue(entity, dr[i], null);
                        }
                    }
                    entityList.Add(entity);
                }
            }
            return entityList;
        }
        #endregion
    }
}
